layui.define(['table','treeTable','tableSelect'],function(exports){

	var $ = layui.$
	,form = layui.form
	,table = layui.table
	,setter = layui.setter
	,tableSelect = layui.tableSelect
	,admin = layui.admin
	,treeTable = layui.treeTable
	var positionColsArr = [
		{ type: 'radio' },
		{ field: 'classcode', title: '类别编码' ,sort:true},
		{ field: 'classname', title: '类别名称' ,sort:true}
	];
	var positionTableHead = '';
	layui.each(positionColsArr,function(inx,val){
		positionTableHead += val.hasOwnProperty('field')?val.field+',':',';
	})
	positionTableHead = positionTableHead.substring(positionTableHead.indexOf(',')+1,positionTableHead.length-1);
	tableSelect.render({
		elem: '#fatherclassname',
		checkedKey: '',
		height:'300',
		width:'150',
		searchType: 'more',
		searchList: [
			{searchKey: 'classcode', searchPlaceholder: '搜索类别编码'},
			{searchKey: 'classname', searchPlaceholder: '搜索类别名称'}
		],
		table: {
			url: layui.setter.host+'/goods_class/getSelectBody'
			,method:'post'
			,where:{'headField':positionTableHead}
			,contentType:'application/json; charset=utf-8'
			,page: true
			,groups:2
			,limit: 20
			,limits:[20,30,50]
			,text: {
				none: '暂无相关数据'
			}
			,cols: [positionColsArr]
		},
		done: function (elem, data) {
			var resultName = []
			var resultValue = []
			layui.each(data.data, function (index, item) {
				resultName.push(item.classname);
				resultValue.push(item.classcode);
			})
			elem.val(resultName.join(","))
			$("input[name='fatherclasscode']").val(resultValue.join(","));
			$("input[name='fatherclassname']").val(resultName.join(","));
		}
	});

	$.ajax({
		url: setter.host+'/unite_platform/goods_class/getclasspurchase',
		type:'post',
		contentType: "application/json; charset=utf-8",
		dataType:'json',
		success: function(res){
			//请求成功后
			if(res.status == setter.response.statusCode.status_Success){
				for(var i=0;i<res.data.id.length;i++){
					$('#classpurchase').append(
							'<option value='+res.data.id[i].id+'>'+res.data.id[i].name+'</option>');
				}
			}else{
				layer.msg(res.msg);
			}
		}
	});


	$.ajax({
		url: setter.host+'/unite_platform/goods_class/getclasslabel',
		type:'post',
		contentType: "application/json; charset=utf-8",
		dataType:'json',
		success: function(res){
			//请求成功后
			if(res.status == setter.response.statusCode.status_Success){

				$('input[name="classlabel"]').val(res.data);
	//			alert($('input[name="classlabel"]').val())
	//			console.log($('input[name="classlabel"]').val())

			}else{
				layer.msg(res.msg);
			}
		}
	});

	$.ajax({
		url: setter.host+'/unite_platform/goods_class/classattribute',
		type:'post',
		contentType: "application/json; charset=utf-8",
		dataType:'json',
		success: function(res){
			//请求成功后
			if(res.status == setter.response.statusCode.status_Success){
			$('input[name="classattribute"]').val(res.data);
			}else{
				layer.msg(res.msg);
			}
		}
	});




	//获取类别等级类型
	var classgradeOptions = "";
	$.ajax({
		url: setter.host+'/goods_class_grade/getSelectBody'
		,type:'post'
		,dataType:'json'
		,data:JSON.stringify({'search':{'flag':'0'}})
		,contentType : 'application/json; charset=utf-8'
		,success: function(res){
			//请求成功后
			if(res.status == setter.response.statusCode.status_Success){
				var data = res.data;
				for (var i = 0; i < data.length; i++) {
					classgradeOptions += '<option value = "' + data[i].value + '">' + data[i].name + '</option>\n';
	            }
			}else{
				layer.msg(res.msg);
			}
		}
	});
    // getTree();
    // function getTree() {
    //     $.ajax({
    //         url: setter.host+'/goods_class/roleList'
    //         ,type:'post'
    //         ,dataType:'json'
    //         ,data:JSON.stringify({})
    //         ,contentType : 'application/json; charset=utf-8'
    //         ,success: function(res){
    //             //请求成功后
    //
    //         }
    //     });
    // }


    loadTable()



//	-------------------------------------------------------------------------------------------
function loadTable(data){

	var roleTable = treeTable.render({
		elem: '#LAY-role-list',
		tree: {
			iconIndex: 0,  // 折叠图标显示在第几列
			idName: 'classcode'  // 自定义id字段的名称
			,arrowType: 'arrow1' //箭头类型
		},
		treeDefaultClose:false,
		treeLinkage:true,
		height: 'full-50',
		cols: colsArr = [
		                 {field: 'classcode', title: '类别编码',width: 180},
		                 {field: 'classname', title: '名称', width: 120},
			{field: 'fatherclasscode', title: '上级', align:'center'},
            {field: 'classflag', title: '状态', align:'center',templet: '#statusTpl'},
		                 ],
	     method:'post',
	     contentType:"application/json; charset=utf-8"
		// ,where:JSON.stringify({})
	     ,url: setter.host+'/goods_class/roleList'
	});


}

//-----------------------------------------------------------------------				

	var classlabelArray = [];
	function  labelarry(){
		classlabelArray.splice(0);
		$('[name="labelvalue"]:checked').each(function(i,obj){
			classlabelArray.push($(obj).val());
		});
	}


	var attrArray = [];
	function  attrarry(){
		attrArray.splice(0);
		$('[name="attributevalue"]:checked').each(function(i,obj){
			attrArray.push($(obj).val());
		});
	}



		var dateType;
//-----------------------------------------------------------------------		

	treeTable.on('row(LAY-role-list)', function(obj){

		var classcode;
		var classname;
		var classgrade;
		var fatherclasscode;
		var classflag;
		var classpurchase;
		var classlabel;
		var classremark;
		var fatherclassname;
		var classattribute;

		dateType='';

		classlabelArray.splice(0);
		attrArray.splice(0);

		var label=  $('input[name="classlabel"]').val().split(',');
		var labelvalue = obj.data.classlabel.split(',');
		$('input[name="classlabel"]').nextAll().remove();
		for(var i = 0; i < label.length; i++){
			var checked = '';
			if(labelvalue.indexOf(label[i]) > -1){
				checked = 'checked';
			}
			$('input[name="classlabel"]').after(
				'<input type="checkbox" '+checked+' lay-skin="primary" name="labelvalue" title="'+label[i]+'" value="'+label[i]+'"/>');
		}

		var attribute=  $('input[name="classattribute"]').val().split(',');
		var attributevalue = obj.data.classattribute.split(',');
		$('input[name="classattribute"]').nextAll().remove();
		for(var i = 0; i < attribute.length; i++){
			var checked = '';
			if(attributevalue.indexOf(attribute[i]) > -1){
				checked = 'checked';
			}
			$('input[name="classattribute"]').after(
				'<input type="checkbox" '+checked+' lay-skin="primary" name="attributevalue" title="'+attribute[i]+'" value="'+attribute[i]+'"/>');
		}


//		console.log(classlabelArray.join(','))
//		$('input[name="classlabel"]').val(classlabelArray.join(','));
//-----------------------------------------------------------------------
		$("#classgrade").val(obj.data.classgrade);
		$("#classcode").val(obj.data.classcode);
		$("#classname").val(obj.data.classname);
		$("#fatherclassname").val(obj.data.fatherclassname);
		$("#fatherclasscode").val(obj.data.fatherclasscode);
		$("#classflag").val(obj.data.classflag);
		$("#classremark").val(obj.data.classremark);
		$("#classpurchase").val(obj.data.classpurchase);
		form.render();
		var classcode;

		fatherclasscode = $("#fatherclasscode").val();

		if(fatherclasscode==-1){
			fatherclasscode=0
		}

var data ={'classcode':fatherclasscode};


		$.ajax({
			url: setter.host+'/unite_platform/goods_class/getclassname',
			type:'post',
			contentType: "application/json; charset=utf-8",
			dataType:'json',
			data:JSON.stringify(data),
			success: function(res){
				//请求成功后
				if(res.status == setter.response.statusCode.status_Success){
					$("#fatherclassname").val(res.data.id[0].classname);
				}else{
					layer.msg(res.msg);
				}
			}
		});


		$("#tableDelete").on("click",function(){
			classcode=obj.data.classcode;
			layer.open({
				content: '是否删除？'
					,btn: ['是', '否']
			,yes: function(index, layero){
				$.ajax({
					url: setter.host+'/unite_platform/goods_class/deleteGoods?classcode='+classcode,
					type:'get',
					contentType: "application/json; charset=utf-8",
					data:{},
					dataType:'json',
					success: function(res){
						//请求成功后
						if(res.status == setter.response.statusCode.status_Success){
							loadTable();
							layer.msg(res.msg);
						}else{
							layer.msg(res.msg);
						}
					}
				});
			}
			,btn3: function(index, layero){
				return false;
			}
			,cancel: function(){
				return false;
			}
			});
		})



		$("#classcode").attr("readonly",true);

		$("#tableInsert").on("click",function(){

			fatherclasscode = $("#classcode").val();
			fatherclassname = $("#classname").val();

			$("#fatherclasscode").val(obj.data.classcode);
			$("#fatherclassname").val(obj.data.classname);

			$("#fatherclasscode").attr("readonly",true);
			$("#fatherclassname").attr("readonly",true);


			$("#classgrade").val(obj.data.classgrade);

			form.val('example', {
		      "classflag": 1
			 ,"classgrade": Number($("#classgrade").val())+1

		    });

			$("#classcode").attr("readonly",false);
			$("#classcode").val("");
			$("#classname").attr("readonly",false);
			$("#classname").val("");
			$("#classremark").attr("readonly",false);
			$("#classremark").val("");
			dateType=$("#tableInsert").attr("data-type");
		})
//		$("#tableEdit").on("click",function(){
//			$("#classname").attr("readonly",false);
//			$("#classremark").attr("readonly",false);
//			dateType=$("#tableEdit").attr("data-type");
//		})
	});



	$('.layui-btn').on('click', function(){
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});


	var active = {
			add: function(){
				dateType='add';
			}
		   ,save:function(){
			form.on('submit(save)', function(data){
				var field = data.field;

				var json;
				labelarry();
				attrarry();
				var modifyUrL ='';
				if(dateType=='add'){
					classcode = $("#classcode").val();
					classname = $("#classname").val();
					classgrade = $("#classgrade option:selected").val();
					classflag = $("#classflag option:selected").val();
					classpurchase = $("#classpurchase option:selected").val();
					classremark = $("#classremark").val();
					fatherclasscode = $("#fatherclasscode").val();
					classlabel = classlabelArray.join(',');
					classattribute =attrArray.join(',');
					modifyUrL = layui.setter.host+'/goods_class/add';

					json={"classcode":classcode,'classname':classname,'classgrade':classgrade,'fatherclasscode':fatherclasscode,'classflag':classflag,
					  'classpurchase':classpurchase,'classlabel':classlabel,'classremark':classremark,'classattribute':classattribute};

				}else{

					classlabel = classlabelArray.join(',');
					classattribute =attrArray.join(',');
					classcode = $("#classcode").val();
					classname = $("#classname").val();
					classgrade = $("#classgrade option:selected").val();
					fatherclasscode = $("#fatherclasscode").val();
					classflag = $("#classflag option:selected").val();
					classpurchase = $("#classpurchase option:selected").val();
					classremark = $("#classremark").val();
					modifyUrL = layui.setter.host+'/goods_class/edit';

					json={"classcode":classcode,'classname':classname,'classgrade':classgrade,'fatherclasscode':fatherclasscode,'classflag':classflag,
				  'classpurchase':classpurchase,'classlabel':classlabel,'classremark':classremark,'classattribute':classattribute};

				}

				layui.admin.req({
					url: modifyUrL
					,type:'post'
					,dataType:'json'
					,contentType: "application/json; charset=utf-8"
					,data:JSON.stringify(json)
					,success: function(res){
//						console.log(res);
						//请求成功后
						if(res.status == setter.response.statusCode.status_Success){
							//刷新树
							loadTable();
							layer.msg(res.msg);
						}else{
							layer.msg(res.msg);
						}
					}

				});
			});
			$('[lay-filter="save"]').trigger('click');
		}

	}


	exports('role',{});
});